package chat;

import java.io.*;
import java.net.*;
import java.util.*;

public class PeerReader extends Thread
{
    private List zLines = new ArrayList();
    private BufferedReader zReader;

    public PeerReader( InputStream pIs )
    {
        IllegalArgument.ifNull( "Is" , pIs );
        zReader = new BufferedReader( new InputStreamReader( pIs ) );
        start();
    }

    private synchronized void add( String pMessage )
    {
        zLines.add( pMessage );
        notifyAll();
    }

    public synchronized String readLine()
    {
        while ( zLines.isEmpty() )
        {
            try
            {
                wait();
            }
            catch ( InterruptedException e )
            {
            }
        }

        Object message = zLines.get( 0 );
        zLines.remove( 0 );
        return (String) message;
    }

    public void run()
    {
        try
        {
            try
            {
                for ( String line ; null != (line = zReader.readLine()) ; )
                    add( line );
            }
            catch ( SocketException ignoreBecauseWeAssumeSocketClosed )
            {
            }
        }
        catch ( IOException e )
        {
            e.printStackTrace();
            System.exit( 1 );
        }
        add( null );
    }
}
